<?php

namespace app\chat\onmessage;

use app\chat\LiveMessage;
use app\zyhsapi\model\ZyhsConsultChatRtcRecord;
use app\zyhsapi\model\ZyhsConsultRtcUserBenefits;
use GatewayWorker\Lib\Gateway;
use Workerman\Lib\Timer;

class AstroConsultLogin
{
    private static $instance = null;
    private $isDebug = false;

    private function __construct($debug)
    {
        $this->isDebug = $debug;
    }

    public static function getInstance(bool $debug = false)
    {
        if (self::$instance === null)
        {
            return new self($debug);
        }

        return self::$instance;
    }

    public function handle(string $clientId = '', $message = [])
    {
        //token解析
        if (isset($message['params']))
        {
            $auth = LiveMessage::zyhsConsultAuth($message['params'], 1, $clientId);
            $auth['action'] = 'astro_consult_login';
            if ($this->isDebug)
            {
                echo "\n";
                echo "==========onMessage action login start==========\n";
                echo "onMessage function client_id:( $clientId )\n";
                echo "auth:(" . json_encode($auth, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ")\n";
                echo "==========onMessage action login end==========\n";
                echo "\n";
            }

            $astrId = $auth['uid'];
            if ($auth['code'] === 200)
            {
                Timer::del($_SESSION['auth_timer_id']);// 认证成功，删除 30关闭连接定时器
                $clientAstrId = LiveMessage::WHO_TYPE_ASTRO . ':' . $astrId;
                if (Gateway::isUidOnline($clientAstrId))
                {
                    Gateway::unbindUid($clientId, $clientAstrId);
                }
                Gateway::bindUid($clientId, $clientAstrId);
                if ($this->isDebug)
                {
                    echo "\n bindUid=success\n";
                }

                $_SESSION['app_type'] = $auth['app_type'];
                $_SESSION['uid'] = $auth['uid'];
                $_SESSION['name'] = $auth['name'];
                $_SESSION['avatar'] = $auth['avatar'];
                $_SESSION['user_type'] = $auth['user_type'];    // 4 => 准了 咨询师
                $_SESSION['login_time'] = time();
                $_SESSION['version'] = $auth['version'];

                $zyhsConsultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
                $astrNowConsultRtcInfo = $zyhsConsultChatRtcRecordModel->getNowRtcDataByCache(2, 1, $astrId);
                if ($astrNowConsultRtcInfo && !$astrNowConsultRtcInfo['id'] && $astrNowConsultRtcInfo['status'] === 1)
                {   // 发送 RTC咨询 待接听 消息
                    $newUserWelfare = (new ZyhsConsultRtcUserBenefits())->getConsultRtcUserBenefits($astrNowConsultRtcInfo['app_type'], $astrNowConsultRtcInfo['uid']);
                    $desc = $newUserWelfare ? sprintf("申请语音咨询(免费%d分钟)…", $newUserWelfare['min']) : '申请语音咨询…';
                    $voiceCallData = [
                        'chat_id' => $astrNowConsultRtcInfo['chat_id'],
                        'app_type' => $astrNowConsultRtcInfo['app_type'],
                        'uid' => $astrNowConsultRtcInfo['uid'],
                        'avatar' => $astrNowConsultRtcInfo['avatar'],
                        'nickname' => $astrNowConsultRtcInfo['nickname'],
                        'status' => 1,
                        'desc' => $desc,
                    ];
                    LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $astrId), LiveMessage::MSG_TYPE_POP_VOICE_CONSULT_CALL, $voiceCallData);
                }
                //发送给当前用户登录成功的消息
                // todo 判断是否有连麦请求  发送 连麦数据
//                Gateway::sendToCurrentClient(LiveMessage::msg($auth['msg'], LiveMessage::MSG_TYPE_LOGIN, [
//                    'user_info' => [
//                        'uen' => $auth['uen'],
//                        'name' => $auth['name'],
//                        'avatar' => $auth['avatar'],
//                        'vip_level' => $auth['vip_level'],
//                        'rank_index' => $auth['rank_index'],
//                        'sign' => $auth['sign']
//                    ]
//                ]));
            } else
            {
                //发送给当前用户登录失败的消息
                Gateway::sendToCurrentClient(LiveMessage::show($auth['code'], $auth['msg'], $message['action']));
            }

        } else
        {
            Gateway::sendToCurrentClient(LiveMessage::show(0, 'params 不能为空！', $message['action']));
        }
    }
}